<template>
  <div class="app-container warehouse-content">
    <EzForm
      ref="menuForm"
      :formMap="formMap"
      v-model="formData"
      @search="searchRequest"
    ></EzForm>
    <BtnGroup ref="btnGroup" :btns="btns" @handle="handleBtnGroup" />
    <!-- 工具栏 end-->

    <div class="">
      <el-table
        ref="table"
        v-loading="loading"
        :data="lists"
        :height="st"
        style="width: 100%"
        row-key="id"
        lazy
        @row-dblclick="dbclick"
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="公告编号" prop="id" width="120">
        </el-table-column>
        <el-table-column label="公告标题" prop="title"> </el-table-column>
        <el-table-column label="公告摘要" prop="summary" width="120">
        </el-table-column>
        <el-table-column label="创建日期" width="160">
          <template slot-scope="scope">{{
            scope.row.created_at | dateJudge
          }}</template>
        </el-table-column>
        <el-table-column label="创建人" prop="created_by"> </el-table-column>
        <el-table-column label="商户简称" prop="merchants_short_name">
        </el-table-column>
        <el-table-column label="仓库名称" prop="warehouse_short_name">
        </el-table-column>
        <el-table-column label="提示力度" prop="prompt_type_cn">
        </el-table-column>
        <el-table-column label="展示日期" width="160">
          <template slot-scope="scope">{{
            scope.row.start_at | dateJudge
          }}</template>
        </el-table-column>
        <el-table-column label="下线日期" width="160">
          <template slot-scope="scope">{{
            scope.row.end_at | dateJudge
          }}</template>
        </el-table-column>

        <el-table-column label="是否展示中">
          <template slot-scope="scope">
            <span>{{ scope.row.under_way_cn }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="editFrom(scope.row)"
              >编辑
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination
        ref="paginationTotal"
        :page="currentPage"
        :total="total"
        :size="pageSize"
        @sizeChange="sizeChange"
        @currentChange="currentChange"
      />
    </div>

    <!-- 新建仓库类型 弹窗 -->
    <el-dialog
      class="add-dialog"
      :visible.sync="dialogVisibleType"
      title="新建公告标签"
      :before-close="modalClose"
      :close-on-press-escape="false"
      append-to-body
    >
      <div>
        <el-form
          ref="typeform"
          :model="typeform"
          label-width="120px"
          size="small"
        >
          <el-form-item
            label="标签名称"
            v-for="(type, tindex) in typeform.type_name"
            :key="tindex"
          >
            <el-input
              style="width: 80%"
              v-model.trim="type.name"
              placeholder="请输入标签名称"
              maxlength="20"
            />
            <!--  :disabled="type.id != ''" -->
            <el-button
              class="del-btn"
              type="text"
              @click="tagDel(tindex, type.id)"
              >删除</el-button
            >
          </el-form-item>
        </el-form>
        <div
          class="add-btn"
          @click="
            typeform.type_name.push({
              name: '',
              id: '',
            })
          "
        >
          添加 +
        </div>
        <div class="tool2" style="margin-top: 45px">
          <el-button type="primary" size="medium" @click="handleSubmitType()"
            >确定</el-button
          >
          <el-button size="medium" @click="modalClose">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
export default {
  components: { Tinymce },
  data() {
    return {
      formMap: [
        {
          label: "公告标题",
          key: "title",
          type: "input",
        },
        {
          label: "公告摘要",
          key: "summary",
          type: "input",
        },
        {
          label: "创建人",
          key: "created_by",
          type: "input",
        },
        {
          label: "创建日期",
          key: "created_at",
          type: "cratedate",
        },
        {
          label: "下线日期",
          key: "expire_time",
          type: "underdate",
        },
        {
          label: "商户简称",
          key: "short_name",
          type: "input",
        },
        {
          label: "仓库名称",
          key: "warehouse_name",
          type: "input",
        },
        {
          label: "提示类型",
          key: "prompt_type",
          type: "select",
          options: [
            { label: "不提示", value: "1" },
            { label: "弱提示", value: "2" },
            { label: "强提示", value: "3" },
          ],
        },
        {
          label: "是否展示中",
          key: "under_way",
          type: "select",
          options: [
            { label: "否", value: "0" },
            { label: "是", value: "1" },
          ],
        },
        // {
        //   label: "商户简称",
        //   key: "phone",
        //   type: "input",
        // },
        // {
        //   label: "仓库名称",
        //   key: "phone",
        //   type: "input",
        // },
      ],
      formData: {
        id: "",
        title: "",
        summary: "",
        prompt_type: "",
        tag_id: "",
        author: "",
        start_created_at: "",
        end_created_at: "",
        created_at: "",
        updated_at: "",
        expire_time: "",
        under_way: "",
        warehouse_name: "",
        short_name: "",
      },
      btns: [
        // { title: "查看日志", pos: "right", handle: "log" },
        { title: "删除", pos: "right", handle: "del" },
        { title: "取消置顶", pos: "right", handle: "close" },
        { title: "设置置顶", pos: "right", handle: "open" },
        { title: "标签管理", pos: "right", handle: "tag" },
        { title: "编辑", pos: "right", handle: "edit" },
        { title: "创建公告", pos: "right", handle: "new" },
      ],

      lists: [],
      dialogloading: true,
      loading: false,
      warehouseDictList: [],
      merchantList: JSON.parse(localStorage.getItem("merchantList")),
      userType: JSON.parse(localStorage.getItem("userType")),
      //新建公告标签
      dialogVisibleType: false, //弹窗
      typeform: {
        type_name: [{ name: "" }],
      },
      tagList: [],
      // 默认显示第几页
      currentPage: 1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      total: 0,
      // 个数选择器（可修改）
      pageSizes: [50, 100, 200],
      // 默认每页显示的条数（可修改）
      pageSize: 30,

      st: 0,
      dialogVisible: false,
      dialogTitle: "创建公告",
      isEdit: false, //是否编辑
      addform: {
        id: "",
        title: "",
        summary: "",
        tag_ids: [],
        merchants_ids: "",
        warehouse_ids: "",
        prompt_type: "",
        sort_num: "",
        content: "",
        author: "",
        start_at: "", //公告开始时间
        end_at: "", //公告下线时间
        state: "1", //状态【1：正常，0：禁止】
      },
      appid: "", //APPID
      appsecret: "", //密钥
      choosePlace: [],
      // 验证表单

      dialogSettingVisible: false,

      place: "",

      in_charge_name: [], //仓库负责人

      country: [],
      userList: [],
    };
  },

  created() {
    this.handleRequest();

    this.dict();
    this.noticeTagDict();
    this.warehouseDict();
    localStorage.removeItem("public");
  },

  mounted() {
    const that = this;
    that.$util.autoHeight(that, that.$refs.table.$el);
  },
  methods: {
    // 标签选择
    tagChange(e) {
      if (e.length > 5) {
        this.$message({ type: "error", message: "标签最多只能选择5条！" });
        this.addform.tag_ids.splice(-1);
      }
    },

    /**
     * 仓库列表字典
     */
    async warehouseDict() {
      const { result } = await this.$.warehouse.warehouseDict({
        warehouse_state: "1",
      });
      this.warehouseDictList = result.warehouseList;
    },
    tagDel(index, ids) {
      let that = this;
      if (!ids) {
        that.typeform.type_name.splice(index, 1);
      } else {
        //请求接口
        async function doAction(index) {
          try {
            that.dialogloading = true;
            const { result } = await that.$.authority.noticeTagDel({
              id: ids,
            });
            that.dialogloading = false;
            that.typeform.type_name.splice(index, 1);
            that.$message({ type: "success", message: "删除成功" });
          } catch (e) {
            that.dialogloading = false;
          }
        }

        this.$confirm("是否确定删除此标签？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            doAction(index, ids);
          })
          .catch(() => {
            //取消的提示
          });
      }
    },
    /**
     * 公告标签字典
     */
    async noticeTagDict() {
      const that = this;
      try {
        const { result } = await that.$.authority.noticeTagDict();
        console.log("result", result);
        if (result.length) {
          that.typeform.type_name = [];
          result.map((item, index) => {
            that.typeform.type_name.push({ name: "", id: "" });
            that.typeform.type_name[index].name = item.name;
            that.typeform.type_name[index].id = item.id;
          });
          console.log("that.typeform.type_name", that.typeform.type_name);
          that.tagList = result;
        }
      } catch (e) {}
    },
    /**
     * 提交类型
     */
    handleSubmitType(e) {
      const that = this;
      that.$refs.typeform.validate(async (v) => {
        if (!v) {
          return false;
        }
        let newForm = that.typeform.type_name;

        try {
          that.dialogloading = true;
          const { result } = await that.$.authority.noticeTagAdd(newForm);
          that.dialogloading = false;
          that.dialogVisibleType = false;

          that.$message({ type: "success", message: "添加成功" });
          that.noticeTagDict();
        } catch (e) {
          that.dialogloading = false;
        }
      });
    },
    /**
     * 头部按钮列表
     */
    handleBtnGroup(evt) {
      let { handle } = evt;
      switch (handle) {
        case "new":
          this.handleCreate();
          break;
        case "open":
          this.settingState(1);
          break;
        case "close":
          this.settingState(0);
          break;
        case "search":
          this.handleRequest();
          break;

        case "tag":
          this.dialogVisibleType = true;
          //富文本
          // this.$refs.tinymce.setContent("");
          break;
        case "log":
          this.toLog();
          break;
        case "del":
          this.delBtn();
          break;
        case "edit":
          this.editFrom();
          break;
        default:
          break;
      }
    },

    /**
     * 查看详情
     */
    editFrom() {
      let obj = {};
      let id = "";
      let ids = [];
      let _selectData = this.$refs.table.selection;
      console.log("_sel", _selectData);
      _selectData.forEach((item, i) => {
        id = item.id;
        ids.push(item.id);
        obj = item;
      });

      if (!id) {
        this.$message({ type: "error", message: "请选择需要操作的公告！" });
        return false;
      }
      if (ids.length > 1) {
        this.$message({ type: "error", message: "仅支持单条公告编辑！" });
        return false;
      }
      obj = JSON.stringify(obj);
      localStorage.setItem("public", obj);
      this.$router.push(`/authority/publicAction`);
    },

    /**
     * 获取商户负责人
     */
    async dict() {
      const { result } = await this.$.warehouse.warehouseDict({});
      console.log("result", result);
      this.userList = result.userList;
    },
    /**
     * 查看日志
     */
    toLog() {
      this.$router.push(`/warehouse/log`);
    },

    /**
     * 设置仓库状态 - 批量 state 暂停-0  开启-1
     */
    delBtn() {
      let that = this;
      let _selectData = that.$refs.table.selection;
      let ids = [];
      let id = "";

      _selectData.forEach((item, i) => {
        id = item.id;
      });

      if (!id) {
        that.$message({ type: "error", message: "请选择需要操作的公告！" });
        return false;
      }

      //请求接口
      async function doAction(id) {
        try {
          that.dialogloading = true;
          const { result } = await that.$.authority.noticeDel({
            id: id,
          });

          that.$message({ type: "success", message: "删除成功" });
          if (result.row == 0) {
            that.$message({ type: "success", message: "未有同意数据" });
          } else {
            that.handleSearch();
          }
        } catch (e) {
          that.dialogloading = false;
        }
      }
      this.$confirm("确定删除此公告, 是否继续?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          doAction(id);
        })
        .catch(() => {
          //取消的提示
        });
    },
    /**
     * 设置仓库状态 - 批量 state 暂停-0  开启-1
     */
    settingState(state) {
      let message = state == 1 ? "设置置顶" : "取消置顶";
      let that = this;
      let _selectData = that.$refs.table.selection;
      let ids = [];
      console.log("_selectData", _selectData, state);
      if (state == 0) {
        _selectData.forEach((item, i) => {
          if (item.is_top == 1) {
            ids.push(item.id);
          }
        });
      } else {
        _selectData.forEach((item, i) => {
          if (item.is_top == 0) {
            ids.push(item.id);
          }
        });
      }
      console.log("_selectData", _selectData, state, ids);
      if (ids.length <= 0) {
        that.$message({ type: "error", message: "请选择需要操作的公告！" });
        return false;
      }

      //请求接口
      async function doAction(ids) {
        try {
          that.dialogloading = true;
          const { result } = await that.$.authority.noticeSetTop({
            id: ids,
            is_top: state,
          });
          that.dialogloading = false;
          that.dialogVisible = false;
          that.$message({ type: "success", message: "修改成功" });
          if (result.row == 0) {
            that.$message({ type: "success", message: "未有同意数据" });
          } else {
            that.handleSearch();
          }
        } catch (e) {
          that.dialogloading = false;
        }
      }
      this.$confirm("确定" + message + "此公告, 是否继续?", "修改状态", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          doAction(ids);
        })
        .catch(() => {
          //取消的提示
        });
    },
    /**
     * 关闭对话框
     */
    modalClose() {
      this.dialogVisible = false;
      this.dialogVisibleType = false;
    },
    /**
     * 显示创建账号弹框
     */
    async handleCreate(e) {
      this.$router.push(`/authority/publicAction`);

      // const that = this;
      // that.dialogloading = false;
      // that.dialogVisible = true;
      // that.isEdit = false;
      // that.choosePlace = [];
    },
    /**
     * 提交创建
     */
    handleSubmit(e) {
      const that = this;
      that.isEdit = false;

      that.$refs.manuForm.validate(async (v) => {
        if (!v) {
          return false;
        }
        // 获取富文本内容
        that.addform.content = that.$refs.tinymce.getContent();
        // console.log("富文本", that.$refs.tinymce.getContent());
        // that.addform.tag_ids = JSON.parse(that.addform.tag_ids);
        // that.addform.warehouse_ids = JSON.parse(that.addform.warehouse_ids);
        // that.addform.merchants_ids = JSON.parse(that.addform.merchants_ids);
        try {
          // that.dialogloading = true;
          // return;
          const { result } = await that.$.authority.noticeAdd(that.addform);
          that.dialogloading = false;
          that.dialogVisible = false;
          that.$message({ type: "success", message: "添加成功" });
          that.handleSearch();
        } catch (e) {
          that.dialogloading = false;
        }
      });
    },
    /**
     * 搜索
     */
    handleSearch(statu) {
      this.currentPage = 1;
      this.handleRequest();
    },
    /**
     * 弹框的行更改
     */
    rowChange(e) {
      console.log(e);
    },
    searchRequest() {
      this.currentPage = 1;
      this.handleRequest();
    },
    sizeChange(e) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = e;
      that.handleRequest();
    },
    currentChange(e) {
      this.currentPage = e;
      this.handleRequest();
    },
    handleSelect() {
      this.currentPage = 1;
      this.handleRequest();
    },
    dbclick(row, event, column) {
      row.isOK = !row.isOK;
      let obj = this.lists.find((i) => {
        return i.id == row.id;
      });
      console.log(row, obj);
    },
    /**
     * 获取列表
     */
    async handleRequest() {
      const that = this;
      const { currentPage, pageSize, formData } = that;
      // console.log(`handleRequest 第${currentPage}页`);
      let o = {
        page_size: pageSize,
        page: currentPage,
      };
      o.start_created_at = !!formData.created_at ? formData.created_at[0] : "";
      o.end_created_at = !!formData.created_at ? formData.created_at[1] : "";

      o.start_at = !!formData.expire_time ? formData.expire_time[0] : "";
      o.end_at = !!formData.expire_time ? formData.expire_time[1] : "";

      that.$util.ext(that.formData, o);

      try {
        that.loading = true;
        const { result } = await that.$.authority.noticeIndex(that.formData);
        that.total = result.pagination.total_count;
        that.$refs.table.bodyWrapper.scrollTop = 0;
        that.lists = result.list;
        result.list.map((item) => {
          item.isOK = false;
          if (!item.length) return;
          that.in_charge_name.push({ name: item.in_charge_name });
        });
        that.loading = false;
      } catch (e) {
        that.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.del-btn {
  margin-left: 20px;
}
.add-btn {
  margin-right: 16%;
  text-align: right;
  cursor: pointer;
  color: #66b1ff;
}
.inp1 {
  flex: 1;
  margin-right: 12px;
}

.supname {
  margin: -18px 0 0 12px;
}

.label {
  font-size: 13px;
  margin-right: 5px;
}
</style>
<style>
.warehouse-content .cell {
  text-align: center;
}
.add-dialog .form-flex .el-form-item__content {
  display: flex;
}
.warehouse-content .front {
}
.warehouse-content .front .el-form-item__content {
  margin-left: 0 !important;
}
.add-dialog .edit-tips {
  color: #c0c4cc;
  font-size: 12px;
  line-height: 1;
  position: absolute;
  padding-top: 2px;
  top: 100%;
  left: 0;
}
.add-dialog .dev-tips {
  color: #c0c4cc;
  font-size: 12px;
  line-height: 1;
  position: absolute;
  top: 100%;
  left: 0;
}
.add-dialog .copy-btn {
  margin-left: 24px;
}
.lzg-dialog-height {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
}

.lzg-dialog-height .el-dialog {
  margin: 0 auto !important;
  height: 90%;
  overflow: hidden;
}
.lzg-dialog-height .el-dialog__body {
  position: absolute;
  left: 0;
  top: 54px;
  bottom: 0;
  right: 0;
  padding: 0;
  z-index: 1;
  overflow: hidden;
  overflow-y: auto;
}
.lzg-dialog-height .el-dialog__body .el-form {
  padding: 24px;
}
</style>
